//
//  NetWorkManager+Extentiton.swift
//  MQLWeibo
//
//  Created by MQL-IT on 2016/11/11.
//  Copyright © 2016年 MQL-IT. All rights reserved.
//

import Foundation

//MARK:封装微博的网络请求方法
extension NetWorkManager {
    
    /// 加载微博数据字典数组
    ///
    ///   - Parameters:
    ///   - since_id: 则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0
    ///   - completion: 完成回调(微博字典数组/是否成功)
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list:[[String:AnyObject]]?, _ isSuccess: Bool)->()) {
        /// 用 网络工具 加载微博数据
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //swift中Int可以转换成AnyObject,但是Int64不行
        let param = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ? max_id - 1 : 0)" ]

        tokenRequest(URLString: urlString, parameters: param as [String : AnyObject]?, completion: {(json, isSuccess) -> () in
            // 从json中获取statuses数组
            // 如果 as?失败 返回nil
            // 提示: 服务器返回的字典数组就是按照时间的倒序的
            let list = (json as? [String:AnyObject])?["statuses"] as? [[String:AnyObject]]
            completion(list, isSuccess)
            
        })
    }
    
    func unreadCount(completion: @escaping (_ count: Int) -> ()) {
        guard let uid = userAccount.uid else { return }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let param = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: param as [String : AnyObject]?) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
    }
    
}
// MARK: - 用户信息
extension NetWorkManager {
    
    /// 加载当前用户信息  - 用户登录后立即执行
    func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject]) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = userAccount.uid else { return }
        let params = ["uid" : uid]
        // 发起网络请求
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            // 完成回调
            completion((json as? [String : AnyObject]) ?? [:] )
        }
    }
}

//MARK: - OAuth相关方法

extension NetWorkManager {
    
    /// 加载AccessToken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调,是否成功
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appKey,"client_secret": appSecret,"grant_type": "authorization_code","code": code,"redirect_uri": redirectUri]
        
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            //直接用字典设置userAccount, 如果请求失败,对原有数据没有影响
            self.userAccount.yy_modelSet(withJSON: json ?? [:])
            printLog(message: self.userAccount)
            
            self.loadUserInfo(completion: { (dict) in
                printLog(message: dict)
                
                // 使用用户信息字典,设置用户(昵称和头像)帐户信息
                self.userAccount.yy_modelSet(with: dict)
                
                //最后保存模型
                self.userAccount.saveAccount()
                // 用户信息加载完成再回调
                completion(isSuccess)
            })
        }
    }
}


